#include "head.h"

// void cleanup_socket(void *p){
//     int *socket_fd = (int *)p;
//     close(*socket_fd);
// }

int net_puts(int socket_fd, thread_status *t_status){
    //thread_status *t_status = (thread_status *)p;
    printf("进入puts\n");
    request_t request = *t_status->request;

    // 发送请求报文
    int ret = send(socket_fd, &request, sizeof(request_t), 0);
    printf("ret = %d\n",ret);
    if(ret == -1){
        printf("puts发送失败\n");
    }
    // 等待响应
    response_t res;
    bzero(&res, sizeof(res));

    //close(socket_fd);

    
    recv(socket_fd, &res, sizeof(res), 0);
    printf("recv after\n");
    if(res.status == 3){
        // 重连失败
        return 3;
    }
    if (res.status == 1)
    {
        // 异常返回
        puts(res.args);
        return -1;
    }
    printf("---响应报文---\n");
    printf("status: %d\n",res.status);
    printf("args: %s\n",res.args);
    printf("-------------\n");
    //发送文件
    send_file(request.args, socket_fd);

    //pthread_cleanup_pop(1);

    pthread_mutex_lock(&t_status->lock);
    int i = 0;
    pthread_t tid = pthread_self();
    for(i = 0; i < t_status->length; i++){
        if(tid == t_status->thread_ids[i]){
            break;
        }
    }
    t_status->status[i] = 0;
    pthread_mutex_unlock(&t_status->lock);
    // 释放临时request
    free(t_status->request);

    return 0;
}
